package com.trs.publish.task;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.trs.publish.Constants.Constants;
import com.trs.publish.domain.LoginLog;
import com.trs.publish.service.LoginLogService;



@Component
public class LoginLogTask{
	
	private final static Logger logger = LoggerFactory.getLogger(LoginLogTask.class);
	
	@Autowired
	private LoginLogService loginLogService;
	
	@Scheduled(cron="*/1 * * * * *")
	public void save(){
		//logger.debug("登录日志保存定时任务运行");
		// 保存登录日志
		if (!Constants.loginLogQueue.isEmpty()) {
			 saveSearchLog();
		}
	}

	private void saveSearchLog() {
		List<LoginLog> list = new ArrayList<LoginLog>();
		try {
			int count = 0;
			while (!Constants.loginLogQueue.isEmpty()
					&& Constants.loginLogQueue.size() > 0) {
				LoginLog loginLog = Constants.loginLogQueue.poll();
				if (loginLog != null) {
					list.add(loginLog);
					count++;
					if (count >= 1000) {
						break;
					}
				}
			}
		} catch (Exception e) {
			logger.error("保存登录日志出错：" + e.getMessage());
		}
		
		if (list != null && list.size() > 0) {
			long startTime = System.currentTimeMillis();
			loginLogService.batchInsert(list);
			long endTime = System.currentTimeMillis();
			logger.info("定时任务批量保存登录日志" + list.size() + "条,耗时" + (endTime - startTime) + "毫秒");
		}
	}    
}   